﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using LuaInterface;

namespace GLuaR.Classes.LuaChecker
{
	/// <summary>
	/// Checks lua scripts.
	/// </summary>
	static class LuaChecker
	{
		public static Lua pLuaVM = null;

		public static void Init()
		{
			pLuaVM = new Lua();
			pLuaVM.DebugHook += new EventHandler<DebugHookEventArgs>(DebugHook);
			pLuaVM.HookException += new EventHandler<HookExceptionEventArgs>(ExceptionHook);
			Program.Output("Loaded LuaInterface.");
		}
		public static void RunFile(string file)
		{
			
			object[] result;
			try
			{
				FileStream curf = System.IO.File.OpenRead(file);
				if (curf.CanRead)
				{
					curf.Close();
					Program.Output("Running lua file");
					result = pLuaVM.DoFile(file);
				}
				
			}
			catch (Exception ex)
			{
				if (ex.Source == "LuaInterface")
					ExceptionHook(pLuaVM, new HookExceptionEventArgs(ex));
				else
					Program.Output("Could not open " + file + ".");
			}
		}
		private static void DebugHook(object sender, DebugHookEventArgs e)
		{
			Program.Output(e.LuaDebug.currentline.ToString());
			Program.Output(e.LuaDebug.name);
			Program.Output(e.LuaDebug.namewhat);
			Program.Output(e.LuaDebug.what);
		}
		private static void ExceptionHook(object sender, HookExceptionEventArgs e)
		{
			Program.Output(e.Exception.Message);
		}
    }
}
